package com.hmdp.utils;


import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

import static com.hmdp.constants.RedisConstants.ORDER_ICR;

/**
 * 全局id生成
 * @author Yhans
 */
@Component
public class RedisIdWorker {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 开始时间戳 2024-2-22 16:20:00
     */
    private static final long BEGIN_TIMESTAMP = 1708618800;
    /**
     * 序列号的位数
     */
    private static final int COUNT_BITS = 32;

    /**
     * 生成全局id
     * @return long 1位符号位+31位时间戳+32位自增redisId
     */
    public long nextId(String keyPrefix) {
        //符号位

        //1.时间戳
        long currentSecond = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC);
        long timestamp = currentSecond - BEGIN_TIMESTAMP;

        //2.自增序列号
        //每天一个key方便统计
        String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        //（不存在空指针）
        long count = stringRedisTemplate.opsForValue().increment(ORDER_ICR + keyPrefix + ":" + date);

        //采用运算符拼接返回

        //向左位移32位 低位补0 加上 id
        return timestamp << COUNT_BITS | count;
    }

}
